package cn.itcast.demo;

import cn.itcast.avro.User;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumWriter;

import java.io.File;
import java.io.IOException;

public class AvroDemo {
    public static void main(String[] args) throws IOException {

        //1.新建对象
        User user1 = new User();
        //2.设置数据
        user1.setName("小明");
        user1.setAddress("上海市");
        user1.setAge(20);
        /**
         * 构造方法添加参数
         */
        User user2 = new User("小红", 7, "red");

        /**
         * Builder方法构建对象
         */
        User user3 = User.newBuilder()
                .setName("小李")
                .setAddress("北京市")
                .setAge(20)
                .build();

        /**
         * 3.序列化操作
         */
        DatumWriter<User> userDatumWriter = new SpecificDatumWriter<>(User.class);
        DataFileWriter<User> dataFileWriter = new DataFileWriter<>(userDatumWriter);
        try {
            dataFileWriter.create(user1.getSchema(), new File("users.avro"));
            dataFileWriter.append(user1);
            dataFileWriter.append(user2);
            dataFileWriter.append(user3);
            dataFileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}